package qinggui.mlz.fileservice.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import qinggui.mlz.module.utils.Response;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Objects;
import java.util.UUID;

/**
 * @author 贺敬彬
 */
@RestController
@RequestMapping
public class FileController {

    // OSS服务的访问域名，它指定了OSS服务的地理位置
    private static final String endpoint = "oss-cn-shenzhen.aliyuncs.com";
    // accessKeyId：阿里云账号的访问密钥ID,和accessKeySecret配合使用
    private static final String accessKeyId = "LTAI5tPgdiTYyUAxsANmMdLb";
    private static final String accessKeySecret = "jTXf3BEj4SJLZKkHyrLM0mKfozFkut";
    // OSS中创建的存储桶（Bucket）的名称
    private static final String bucketName = "shangchuanfile";


    /**
     * 文件上传到阿里云OSS
     *
     * @param file 文件类型
     * @return String
     */
    @PostMapping("file/uploadOSS")
    public Response<String> uploadOSS(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return new Response<>(4004, "文件不能为空");
        }
        // 限制文件大小不超过5GB
        if (file.getSize() > 5 * 1024 * 1024 * 1024) {
            return new Response<>(4004, "文件不能大于5GB");
        }
        // 获取后缀名
        String extName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        // 获取当前的时间，格式为yyyyMMdd
        String time = LocalDate.now().toString();
        // 2025-07-02,帮我截取成这种格式yymm/dd/
        time = time.substring(2, 4) + time.substring(5, 7) + "/" + time.substring(8, 10);
        // 获取随机唯一字符串
        String uuid = UUID.randomUUID().toString();
        // 去除对应的-
        uuid = uuid.replaceAll("-", "");
        String finalfile;
        if (extName.equals(".jpg") || extName.equals(".jpeg") || extName.equals(".png") || extName.equals(".gif") || extName.equals(".bmp") || extName.equals(".tiff")) {
            // 获取图片的长度和宽度
            BufferedImage read = null;
            try {
                read = ImageIO.read(file.getInputStream());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            int width = read.getWidth();
            int height = read.getHeight();
            finalfile = "image" + "/" + time + "/" + uuid + "_" + width + "x" + height + extName;
        } else {
            finalfile = "file" + "/" + time + "/" + uuid + extName;
        }
        // 将格式好的文件保存到阿里云OSS
        // 创建OSS客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, finalfile, file.getInputStream());
        } catch (OSSException e) {
            System.out.println(e.getMessage());
            return new Response<>(4004, "文件上传失败");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            ossClient.shutdown();
        }
        // 返回文件的地址
        return new Response<>(1001, "http://" + bucketName + "." + endpoint + "/" + finalfile);
    }

    /**
     * 文件上传到本地
     *
     * @param file 文件类型
     * @return String
     */
    @PostMapping("file/upload")
    public Response<String> uploadImage(@RequestParam("file") MultipartFile file) {
        // 指定E盘上的upload目录，将上传的文件保存到该目录下
        String uploadPath = "E:/upload/";
        // 判断当前目录是否存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        // 获取上传的文件源名称
        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename=" + originalFilename);
        // 随机生成一个字符串作为新的文件名称
        String fileName = UUID.randomUUID().toString();
        // 获取上传给服务器的文件对应的后缀扩展名
        String extName = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf("."));
        // 完成文件名称,包含文件后缀
        fileName = fileName + extName;
        // upload目录下创建指定的文件:fullFileName文件
        // 在dir目录下创建指定的文件:fullFileName文件
        Path fullFileName = Paths.get(uploadPath, fileName);
        // 将上传文件的数据写入到fullFileName文件中
        try {
            file.transferTo(fullFileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new Response<>(1001,"文件上传成功");
    }
}